#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

# 依赖库：PyMySQL

# 从mysql数据库中提取源文件间的def-use依赖，包括全局函数调用与全局变量使用

import pymysql
import utils.db
import utils.def_parse

db_config = utils.def_parse.def2map("../mysql_config.def")

# print(db_config)
# exit(1)

db = pymysql.connect(
  host=db_config['HOST']            # 数据库主机地址
  ,user=db_config['USER']           # 数据库用户名
  ,password=db_config['PASSWORD']   # 数据库密码
  ,database=db_config['DATABASE']   # 数据库名称
  ,port=int(db_config['PORT'])           # 数据库端口, 默认为3306
)
 
print(db)

Step0_CompressSymbolUse =                                 utils.db.get_sql("./sql/steps/0_CompressSymbolUse.sql")
Step1_ExtractSymbolDependencyBetweenModules =             utils.db.get_sql("./sql/steps/1_ExtractSymbolDependencyBetweenModules.sql")
Step1_ExtractSymbolDependencyBetweenModules_Compressed =  utils.db.get_sql("./sql/steps/1_ExtractSymbolDependencyBetweenModules_Compressed.sql")
Step2_FindVirtualFunctionTargets =                        utils.db.get_sql("./sql/steps/2_FindVirtualFunctionTargets.sql")
Step2_FindVirtualFunctionTargets_Compressed =             utils.db.get_sql("./sql/steps/2_FindVirtualFunctionTargets_Compressed.sql")
Step3_ExtractModuleDependency =                           utils.db.get_sql("./sql/steps/3_ExtractModuleDependency.sql")
AutoTruncate =                                            utils.db.get_sql("./sql/steps/AutoTruncate.sql")

mycursor = db.cursor()

try:
  for cmd in AutoTruncate:
        mycursor.execute(cmd)
  for cmd in Step0_CompressSymbolUse:
        mycursor.execute(cmd)
  for cmd in Step1_ExtractSymbolDependencyBetweenModules:
        mycursor.execute(cmd)
  for cmd in Step3_ExtractModuleDependency:
        mycursor.execute(cmd)
  
except Exception as e:
  # 出错时数据库回滚
  db.rollback()
  print(f"Exception {e} happened.")
  
else:
  # 提交事务
  db.commit()
  mycursor.execute("SELECT from_module, to_module, degree, dependency_tag from ModuleDependency;")
  myresult = mycursor.fetchall()
  for x in myresult:
        print(f'depends {x[0]} {x[1]}')
        
  # 关闭数据库连接
  db.close()
  print("Success.")
